package stardust.product.platform.webc.log;


import stardust.product.platform.webc.WebcFilter;
import stardust.product.platform.webc.WebcRequestHandler;
import stardust.product.platform.webc.WebcResourceReference;


public class LogFilter implements WebcFilter
{
  
  private ThreadLocal<RequestSnapshot> currentSnapshot = new ThreadLocal<RequestSnapshot>();
  private ThreadLocal<Long> currentRequestTime = new ThreadLocal<Long>();
  
  public boolean doBeforeFilter(String uri, WebcRequestHandler request, WebcResourceReference reference)
  {
    // 增量访问计数器。
    reference.getAccessLog().incrementAccess();
    
    /*
     * 创建请求快照和保存请求开始的时间。
     */
    this.currentSnapshot.set(RequestSnapshot.createRequestSnapshot(request));
    this.currentRequestTime.set(System.currentTimeMillis());
    
    return true;
  }

  public void doAfterFilter(String uri, WebcRequestHandler request, WebcResourceReference reference, Object returnValue, Throwable exception)
  {
    /*
     * 保存请求错误信息。
     */
    if (exception != null)
    {
      reference.getAccessLog().errorOccurred(exception);
    }
    
    /*
     * 获取当前请求的快照和计算请求处理耗时，并更新耗时计数器和请求日志。
     */
    RequestSnapshot snapshot = this.currentSnapshot.get();
    long consumptionTime = System.currentTimeMillis() - this.currentRequestTime.get();
    
    reference.getAccessLog().incrementConsumptionTime(consumptionTime);
    
    if (snapshot != null)
    {
      snapshot.setConsumptionTime(consumptionTime);
//      reference.getAccessLog().putSnapshot(snapshot);
    }
  }

}
